<?php
/**
 * Description:
 *
 * @author      Eden
 * @datetime    2016/12/26 22:41
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class List_Model extends WX_Model
{

    protected $width = 640;
    protected $height = 360;
    private $total = 0;

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }


    /**
     * 获取总数
     * @return int
     */
    public function getTotal()
    {
        return intval($this->total);
    }

    /**
     * 获取列表
     * @param int $offset
     * @param int $limit
     * @return array
     */
    public function getLists($userid, $offset = 0, $limit = 20)
    {
        $tDb = clone($this->db);
        $this->total = $tDb->where('status', 1)->where("stock > 0")->count_all_results('base_goods');

        $db = clone($this->db);
        $q = $db->select('id, goodsName, thumb, thumbWidth, thumbHeight, expressWeight, streamId, minPrice, created')
            ->from('base_goods')
            ->order_by('modified', 'DESC')
            ->limit($limit, $offset)
            ->order_by('created', 'DESC')
            ->where(array('status' => 1))
            ->where("stock > 0")
            ->get();

        $rows = $q->result_array();
        if (empty($rows)){
            return [];
        }

        $results = $goodsIds = [];
        foreach($rows as $item) {
            $wh = $this->countWidthHeight($item['thumbWidth'], $item['thumbHeight']);
            array_push($goodsIds, $item['id']);
            $results[] = array(
                'goodsId' => intval($item['id']),
                'goodsName' => value($item, 'goodsName'),
                'thumb' => thumb($item['thumb'], $wh['width'], $wh['height']),
                'width' => $wh['width'],
                'height' => $wh['height'],
                'price' => money_format('%i', $item['minPrice'] / 100),
                'expressWeight' => doubleval($item['expressWeight']),
                'created' => formateTimeStamp($item['created']),
                'isCollected' => false,
                'isAddToCar' => false,
                'isLive' => !empty($item['streamId']),
                'collected' => false
            );
        }

        // 检查收藏
        $this->_getCollected($results, $userid, $goodsIds);
        return $results;
    }

    private function _getCollected (&$results, $userid, $ids)
    {
        $db = clone($this->db);
        $db->where_in('goodsId', $ids);
        $db->where('userId', $userid);
        $q = $db->get('user_collect');
        $rows = $q->result_array();
        if (empty($rows)) {
            return null;
        }

        $gids = [];
        foreach ($rows as $item) {
            $gids[] = $item['goodsId'];
        }

        foreach ($results as &$item) {
            $item['collected'] = in_array($item['goodsId'], $gids);
        }
    }

}
